<?php

class GroupParserController extends Controller_Action
{
	public function indexAction()
	{
		// Получаем группу и очередь, но не обижаемся, если они не выбраны, 
		// они будут отображены в форме
		$groupRow = null;
		$turnRow = null;
		$this->view->turns = array();
		try {
			$groupRow = $this->_getGroupRow();
			$turnRow = $this->_getTurnRow();
			$this->view->turns = $groupRow->getTurnRowset();
		} catch (Zend_Navigation_Exception $e) {
			
		}
		
		$this->view->currentGroup = $groupRow;
		$this->view->currentTurn = $turnRow;
		
		// Далее продолжаем только если форма еще не была отправлена
		if (!$this->getRequest()->isPost()) {
			return;
		}
		
		if (!$this->_getParam('group_url')) {
			throw new Zend_Controller_Action_Exception('Не указан адресс группы');
		}
		$group = VkApi::getInstance()->getGroupById($this->_getParam('group_url'));
		//$this->_log->info('Parse community get posts: vk api request (groups.getById) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
		
		$posts_count = ($this->_getParam('posts_count')) ? $this->_getParam('posts_count') : 100;
		$posts_offset = ($this->_getParam('posts_offset')) ? $this->_getParam('posts_offset') : 0;
		$likes_min = (!$this->_getParam('likes_min') || $this->_getParam('likes_min') == 0) ? 0 : $this->_getParam('likes_min');
		$commerical = ($this->_getParam('commerical')) ? $this->_getParam('commerical') : true;
		
		$query = array(
				'owner_id' => '-' . $group['gid'],
				'offset' => $posts_offset,
				'count' => $posts_count,
				'filter' => 'all',
		);
		$posts = VkApi::getInstance()->getWallPosts($query);
		//$this->_log->info('Parse community get posts: vk api request (groups.getById) params (' . $this->_vk->getStrParams() . '); response=' . $this->_vk->getStrResponse());
		
		// Удаляем из выдачи те посты, которые мы уже добавляли, чтобы избежать дубликатов.
		$postIds = array_keys($posts);
		$select = PostPeer::getInstance()->select()->where('external_id in (?)', $postIds);
		$rowset = PostPeer::getInstance()->fetchAll($select);
		foreach ($rowset as $row) {
			$id = $row->getId();
			
			if (isset($posts[$id])) {
				unset($posts[$id]);
			}
		}
		
		$result = array();
		foreach($posts as $post) {
			if (is_int($post)) continue;
			if ($post['likes']['count'] < $likes_min) continue;
				
			// Проверить на рекламу
			if ($commerical) {
				if (isset($post['copy_owner_id'])) {
					continue;
				}
				if (preg_match('/\[club(.*)\]*/i', $post['text'])) {
					continue;
				}
				if (preg_match('/(vk\.|vkontakte\.)/i', $post['text'])) {
					continue;
				}
				if (preg_match('/(http)/i', $post['text'])) {
					continue;
				}
			}
			
			$img = isset($post['attachment']['photo']['src_big']) ? $post['attachment']['photo']['src_big'] : null;
			$result[$post['id']] = array(
					'id' => $post['id'],
					'text' => $post['text'],
					'likes' => $post['likes']['count'],
					'reposts' => $post['reposts']['count'],
					'date' => date('Y-m-d H:i:s', $post['date']),
					'img' => $img,
					'tag' => $group['name']
			);
		}
		
		$this->view->posts = $result;
	}
}
